package com.igeek.compus.backend.web.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.igeek.compus.backend.menu.entity.Menu;
import com.igeek.compus.backend.menu.service.MenuService;
import com.igeek.compus.backend.notice.service.NoticeService;
import com.igeek.compus.backend.seller.entity.Seller;
import com.igeek.compus.backend.seller.service.SellerService;
import com.igeek.compus.backend.system.Constants;
import com.igeek.compus.backend.system.R;
import com.igeek.compus.backend.system.properties.WxConfig;
import com.igeek.compus.backend.system.utils.JedisUtil;
import com.igeek.compus.backend.user.entity.User;
import com.igeek.compus.backend.user.service.UserService;
import com.igeek.compus.backend.web.service.WebService;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 这里代码都是为小程序服务，后面要挪到web模块
 */
@Slf4j
@RestController
@RequestMapping("web")
public class WebController {

    @Autowired
    private JedisUtil jedisUtil;

    @Autowired
    private MenuService menuService;

    @Autowired
    private WebService webService;

    @Autowired
    private NoticeService noticeService;

    @Autowired
    private UserService userService;

    @RequestMapping("login")
    public R login(String code) {

        try {
            WxConfig wxConfig = WxConfig.getInstance();
            String url = wxConfig.getProperty("wx.auth.code2Session");
            Map<String, Object> map = new HashMap<>();
            map.put("appid", wxConfig.getProperty("wx.appid"));
            map.put("secret", wxConfig.getProperty("wx.secret"));
            map.put("js_code", code);
            map.put("grant_type", "authorization_code");
            String res = HttpUtil.createGet(url).form(map).execute().body();

            JSONObject resObj = JSONObject.parseObject(res);
            String openId = (String) resObj.get("openid");

            User userInDb = userService.getUserInfoByOpenId(openId);
            if(userInDb == null) {
                User user = new User();
                user.setOpenId(openId);
                userService.addUser(user);

                System.out.println(user.getId());

                R r = new R();
                r.setCode(3);
                r.setData(user);
                return r;
            }
            return R.success(userInDb);
        }catch (Exception e) {
            log.error("web login异常：" + e);
            return R.error();
        }
    }

    /**
     * (web)首页获得菜单列表
     * 1.先去redis中查询菜单列表
     * 2.如果有，则直接返回，如果没有，先去数据库中查询
     * 3.把数据库中查询的数据放入redis
     *
     * @return
     */
    @RequestMapping("getMenuList")
    public Map getMenuList() {
        Map<String, Object> result = new HashMap<>();
        JSONArray menuArray = null;

        // 获得redis中的菜单列表
        String menuListFromRedis = jedisUtil.get("sys_menuList");

        if (StrUtil.isNotEmpty(menuListFromRedis)) {
            // redis中数据存在,直接返回
            menuArray = JSONArray.parseArray(menuListFromRedis);
        } else {
            // 从数据库中获得菜单列表
            List<Menu> menuList = menuService.getMenuListByPage(new Menu());
            // 组装成jsonArray字符串存入redis中
            menuArray = new JSONArray();
            for (Menu menu : menuList) {
                JSONObject menuObj = new JSONObject();

                menuObj.put("menuName", menu.getMenuName());
                menuObj.put("url", menu.getUrl());
                menuObj.put("imageUrl", menu.getImageUrl());

                menuArray.add(menuObj);
            }
            System.out.println(menuArray.toJSONString());
            jedisUtil.set("sys_menuList", menuArray.toJSONString());
        }

        result.put(Constants.RETDATA, menuArray);
        result.put(Constants.RETCODE, Constants.SUCCESS_CODE);
        result.put(Constants.RETMSG, Constants.SUCCESS_MSG);

        return result;
    }

    /**
     * 用户注册成为卖家
     *
     * @return
     */
    @RequestMapping("registerSeller.do")
    public R registerSeller(Seller seller) {

        try {
            String url = "http://121.5.145.35:8080/web/upstream/check";
            Map<String, Object> map = new HashMap<>();
            map.put("idCard", 100);
            map.put("studentNo", 200);
            map.put("realName", 100);
            map.put("schoolName", 200);
            String result = HttpUtil.createGet(url).form(map).execute().body();

            JSONObject resultObj = JSONObject.parseObject(result);
            String code = (String) resultObj.get("code");
            if ("0".equals(code)) {
                webService.registerSeller(seller);
                return R.success();
            }
            return R.fail((String) resultObj.get("msg"));
        } catch (Exception e) {
            log.error("web reisterSeller错误：" + e);
            return R.fail("系统错误");
        }
    }

    @RequestMapping("getNoticeList")
    public R getNoticeList(String type) {

        if (StrUtil.isEmpty(type)) {
            return R.fail("参数异常");
        }
//        {
//            "notifyNumber": 99,
//            "noticeList":[{},{}]
//        }

        if ("1".equals(type)) {
            // 返回学校通知
        } else if ("2".equals(type)) {
            // 返回服务通知
        } else {
            // 返回互动消息
        }
        return null;
    }

}
